package com.android.lovely.ui.fragment.role

import android.Manifest
import android.app.Activity
import android.net.Uri
import android.os.Build
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat.getString
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.whenResumed
import androidx.recyclerview.widget.GridLayoutManager
import com.android.lovely.R
import com.android.lovely.const.CreatedRoleRefresh
import com.android.lovely.const.FinishCreateRole
import com.android.lovely.databinding.FragmentCreateRoleFiveBinding
import com.android.lovely.databinding.ItemRoleSelectCardBinding
import com.android.lovely.ext.loadWithPlaceholder
import com.android.lovely.ext.startImageCrop
import com.android.lovely.framework.BaseAdapter
import com.android.lovely.room.role.CreateRole
import com.android.lovely.room.role.NewCard
import com.android.lovely.room.role.NewPrice
import com.android.lovely.ui.activity.AiGenerationActivity
import com.android.lovely.ui.activity.CreateRolePreviewActivity
import com.android.lovely.ui.activity.CreateWorkActivity
import com.android.lovely.ui.activity.HomeActivity
import com.android.lovely.ui.dialog.UpLoadDialog
import com.android.lovely.ui.dialog.showLovelyDialog
import com.android.lovely.ui.viewmodel.CreateRoleViewModel
import com.android.lovely.ui.widget.CreateRoleBottomWidget.OnBottomClickListener
import com.kotlin.extensions.bus.FlowBus
import com.kotlin.extensions.bus.post
import com.kotlin.extensions.context.ContextExt.startPage
import com.kotlin.extensions.context.ContextExt.startPageClearTop
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.keyboard.hideKeyboard
import com.kotlin.extensions.view.ViewExt.clickable
import com.yalantis.ucrop.UCrop
import kotlinx.coroutines.flow.collectLatest
import java.util.Collections

/**
 *
 * @author why
 * @date 2025/4/5 21:20
 */
class CreateRoleStep5Fragment: CreateRoleBaseFragment<FragmentCreateRoleFiveBinding>() {

    val adapter by lazy {
        SnapCardAdapter()
    }

    override fun initView() {
        mBinding.clBottom.setPreviewText(if(viewModel.isQuick) getString(R.string.submit) else getString(R.string.preview))
        mBinding.clBottom.update(viewModel.isEdit || viewModel.isQuick, object : OnBottomClickListener{
            override fun onPreview() {
                if (viewModel.isQuick) {
                    save()
                    viewModel.save()
                    submit()
                } else {
                    save()
                    viewLifecycleOwner.lifecycleScope.launchSafety {
                        viewModel.save()
                        activity?.finish()
                    }
                }
            }

            override fun onNext() {
                save()
                lifecycleScope.launchSafety {
                    viewModel.save()
                    startPage<CreateRolePreviewActivity>("role_id" to viewModel.id)
                }
            }

            override fun onBack() {
                viewModel.preStep(4)
            }
        })

        mBinding.clGeneration.clickable {
            startPage<AiGenerationActivity>()
        }
        mBinding.aiTask.clickable {
            startPage<CreateWorkActivity>(
                "task" to true
            )
        }

        mBinding.rv.layoutManager = GridLayoutManager(requireContext(), 2)
        mBinding.rv.adapter = adapter
        adapter.setOnRemoveCallback {
            checkEnable()
        }

        mBinding.clUpload.clickable {
            requireActivity().hideKeyboard()
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                avatarSelectionLauncher.launch("image/*")
                return@clickable
            }
            storagePermissionRequestLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
        }

        lifecycleScope.launchSafety {
            viewModel.cardPrice.collectLatest {
                adapter.priceList = it.list.orEmpty()
                adapter.maxCardLimit = it.maxCardNum ?: 1
                adapter.notifyDataSetChanged()
            }
        }

        viewModel.getCardPrice()

    }

    override fun update(it: CreateRole) {
        mBinding.clBottom.update(viewModel.isEdit || viewModel.isQuick)
        mBinding.clBottom.setPreviewText(if(viewModel.isQuick) getString(R.string.submit) else getString(R.string.preview))
        adapter.updateList(it.cards)
        checkEnable()
    }

    private fun submit() {
        requireActivity().showLovelyDialog {
            setDialogTitle(getString(R.string.role_submit_18))
            setPositiveButton {
                lifecycleScope.launchSafety {
                    val dialog = UpLoadDialog().apply {
                        arguments = bundleOf("isEdit" to false,
                            "role_id" to viewModel.id)
                    }
                    dialog.show(requireActivity().supportFragmentManager)
                    runCatching {
                        val success = viewModel.createRole()
                        dialog.dismissAllowingStateLoss()
                        if (success) {
                            lifecycle.whenResumed {
                                requireActivity().startPageClearTop<HomeActivity>("position" to 3,
                                    "role" to (viewModel.createRole?.public ?: true)
                                )
                                FlowBus.post(CreatedRoleRefresh())
                                FlowBus.post(FinishCreateRole())
                            }
                        }
                    }
                }
            }
        }
    }

    // 存储权限请求启动器
    private val storagePermissionRequestLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isPermissionGranted ->
        handleStoragePermissionRequestResult(isPermissionGranted)
    }

    // 裁剪活动启动器
    private val imageCropActivityLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->
        handleImageCropActivityResult(activityResult)
    }

    // 头像选择启动器
    private val avatarSelectionLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) { selectedAvatarUri ->
        handleAvatarSelectionResult(selectedAvatarUri)
    }

    // 处理存储权限请求结果
    private fun handleStoragePermissionRequestResult(isPermissionGranted: Boolean) {
        if (isPermissionGranted) {
            startAvatarSelection()
        }
    }

    // 处理裁剪活动结果
    private fun handleImageCropActivityResult(activityResult: ActivityResult) {
        if (activityResult.resultCode == Activity.RESULT_OK) {
            val resultIntent = activityResult.data ?: return
            val croppedAvatarUri = UCrop.getOutput(resultIntent) ?: return
            val path = croppedAvatarUri.path ?: return
            val width = UCrop.getOutputImageWidth(resultIntent)
            val height = UCrop.getOutputImageHeight(resultIntent)
            adapter.insert(NewCard(path, width = width, height = height))
        }
        checkEnable()
    }

    // 处理头像选择结果
    private fun handleAvatarSelectionResult(selectedAvatarUri: Uri?) {
        selectedAvatarUri?.let {
            startImageCrop(it)
        }
    }

    // 启动头像选择
    private fun startAvatarSelection() {
        avatarSelectionLauncher.launch("image/*")
    }

    // 启动图片裁剪
    private fun startImageCrop(avatarUri: Uri) {
        requireActivity().startImageCrop(
            imageCropActivityLauncher, avatarUri,9, 16, isCircleCrop = false, )
    }

    private fun checkEnable() {
        var isEnable = true
        if(adapter.getItems().isEmpty()) {
            isEnable = false
        }

        mBinding.clBottom.updateEnable(isEnable)
    }

    override fun save() {
        viewModel.updateRole {
            cards = adapter.getItems()
        }
    }

    override fun hasEdit(): Boolean {
        return viewModel.createRole?.cards != adapter.getItems()
    }

    override fun onKeyBoardChange(progress: Int) {

    }

    override suspend fun initData() {

    }
}

class SnapCardAdapter : BaseAdapter<NewCard, ItemRoleSelectCardBinding>() {

    var priceList: List<NewPrice> = emptyList()

    var maxCardLimit: Int = 1

    private var onRemoveCallback: () -> Unit = {}

    override fun bindViewWithHolderDetails(
        holder: ViewHolder,
        item: NewCard?,
        binding: ItemRoleSelectCardBinding,
        position: Int
    ) {
        item ?: return

        with(holder.binding) {
            setupCardImage(item)
            setupMoveButton(position)
            setupPriceInfo(position)
            setupRemoveButton(position)
        }
    }

    // 提取图片设置逻辑
    private fun ItemRoleSelectCardBinding.setupCardImage(item: NewCard) {
        val imagePath = item.localePath.ifEmpty { item.url }
        image.loadWithPlaceholder(imagePath, R.drawable.icon_item_holder)
    }

    // 提取移动按钮逻辑
    private fun ItemRoleSelectCardBinding.setupMoveButton(position: Int) {
        move.isSelected = position == 0
        move.isClickable = position > 0
        move.clickable { moveItemToFirst(position) }
    }

    private fun ItemRoleSelectCardBinding.setupPriceInfo(position: Int) {
        container.isVisible = position in 1 until priceList.size

        if (position < priceList.size) {
            val (point, intimacy) = priceList[position].let { it.point to it.intimacy }

            heart.isVisible = intimacy > 0
            tvOr.isVisible = intimacy > 0 && point > 0
            gemUnlock.isVisible = point > 0

            gemUnlock.text = point.toString()
            heart.text = intimacy.toString()
        }
    }

    private fun ItemRoleSelectCardBinding.setupRemoveButton(position: Int) {
        remove.clickable {
            deleteAt(position)
            onRemoveCallback()
        }
    }

    private fun moveItemToFirst(fromPosition: Int) {
        if (fromPosition <= 0) return

        getItems().apply {
            repeat(fromPosition) { i ->
                Collections.swap(this, fromPosition - i, fromPosition - i - 1)
            }
        }

        notifyItemMoved(fromPosition, 0)
        notifyDataSetChanged()
    }

    fun setOnRemoveCallback(callback: () -> Unit) {
        onRemoveCallback = callback
    }
}